package com.brillilab.message.consumer;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.brillilab.common.rocketmq.OnsMessageEnum;
import com.brillilab.common.rocketmq.OnsMessageVo;
import com.brillilab.message.handler.MessageHandler;
import org.springframework.stereotype.Component;

/**
 * 广播消息监听器
 * 当使用广播消费模式时，消息队列 RocketMQ 会将每条消息推送给集群内所有注册过的客户端，保证消息至少被每台机器消费一次。
 *
 * @author lj
 */
@Component
public class OnsBroadcastListener implements MessageListener {

    public static MessageHandler messageHandler;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        // 此处可以写具体业务逻辑，body是具体发送的内容
        try {
            OnsMessageVo onsMqVo = JSONObject.parseObject(new String(message.getBody()), OnsMessageVo.class);
            if (OnsMessageEnum.UNLOCK.getType().equals(onsMqVo.getType()) ||
                    OnsMessageEnum.UNLOCK_POWER.getType().equals(onsMqVo.getType())) {
                messageHandler.handler(onsMqVo.getTitle(), onsMqVo.getDeviceNos(), onsMqVo.getData());
            } else if (OnsMessageEnum.PUSH_NOTICE.getType().equals(onsMqVo.getType())) {
                //推送通知
                messageHandler.handler(onsMqVo.getMessageData(), MessageHandler.AIO);
            } else if (OnsMessageEnum.PUSH_MESSAGE.getType().equals(onsMqVo.getType())) {
                //推送消息
                messageHandler.handler(onsMqVo.getMessageData(), MessageHandler.AIO);
            }
            return Action.CommitMessage;
        } catch (Exception e) {
            return Action.CommitMessage;
        }
    }

}
